/**
 * WebSocket管理工具类
 */
class WebSocketManager {
	constructor() {
		this.socketTask = null;
		this.isConnected = false;
		this.reconnectTimer = null;
		this.heartbeatTimer = null;
		this.messageHandlers = new Map(); // 存储消息处理器
		this.reconnectCount = 0;
		this.maxReconnectCount = 5;
		this.reconnectInterval = 3000;
		this.heartbeatInterval = 30000;
		this.wsUrl = 'ws://your-websocket-server.com'; // 请替换为实际的WebSocket服务器地址
	}

	/**
	 * 连接WebSocket
	 * @param {Object} options 连接选项
	 * @param {string} options.url WebSocket服务器地址
	 * @param {Object} options.header 请求头
	 * @param {string} options.chatId 聊天房间ID
	 */
	connect(options = {}) {
		if (this.socketTask) {
			this.disconnect();
		}

		const { url, header, chatId } = options;
		const wsUrl = url || this.wsUrl;
		
		console.log('正在连接WebSocket:', wsUrl);

		this.socketTask = uni.connectSocket({
			url: chatId ? `${wsUrl}/chat/${chatId}` : wsUrl,
			header: header || {},
			success: () => {
				console.log('WebSocket连接成功');
			},
			fail: (err) => {
				console.error('WebSocket连接失败:', err);
				this.handleConnectionError();
			}
		});

		this.setupEventListeners();
	}

	/**
	 * 设置事件监听器
	 */
	setupEventListeners() {
		if (!this.socketTask) return;

		// 连接打开
		this.socketTask.onOpen(() => {
			console.log('WebSocket连接已打开');
			this.isConnected = true;
			this.reconnectCount = 0;
			this.startHeartbeat();
			this.notifyHandlers('open', null);
		});

		// 接收消息
		this.socketTask.onMessage((res) => {
			try {
				const data = JSON.parse(res.data);
				console.log('收到WebSocket消息:', data);
				this.handleMessage(data);
			} catch (error) {
				console.error('解析WebSocket消息失败:', error);
			}
		});

		// 连接错误
		this.socketTask.onError((err) => {
			console.error('WebSocket错误:', err);
			this.isConnected = false;
			this.notifyHandlers('error', err);
			this.handleConnectionError();
		});

		// 连接关闭
		this.socketTask.onClose((res) => {
			console.log('WebSocket连接已关闭', res);
			this.isConnected = false;
			this.clearHeartbeat();
			this.notifyHandlers('close', res);
			
			// 如果不是主动关闭，则尝试重连
			if (res.code !== 1000) {
				this.handleConnectionError();
			}
		});
	}

	/**
	 * 处理连接错误
	 */
	handleConnectionError() {
		if (this.reconnectCount < this.maxReconnectCount) {
			this.scheduleReconnect();
		} else {
			console.error('WebSocket重连次数已达上限');
			this.notifyHandlers('maxReconnectReached', null);
		}
	}

	/**
	 * 计划重连
	 */
	scheduleReconnect() {
		this.clearReconnectTimer();
		this.reconnectCount++;
		
		console.log(`准备第${this.reconnectCount}次重连，${this.reconnectInterval}ms后执行`);
		
		this.reconnectTimer = setTimeout(() => {
			if (!this.isConnected) {
				console.log(`执行第${this.reconnectCount}次重连`);
				this.connect();
			}
		}, this.reconnectInterval);
	}

	/**
	 * 断开连接
	 */
	disconnect() {
		if (this.socketTask) {
			this.socketTask.close({
				code: 1000,
				reason: '主动断开连接'
			});
			this.socketTask = null;
		}
		this.isConnected = false;
		this.clearHeartbeat();
		this.clearReconnectTimer();
	}

	/**
	 * 发送消息
	 * @param {Object} data 要发送的数据
	 */
	send(data) {
		if (this.socketTask && this.isConnected) {
			const message = typeof data === 'string' ? data : JSON.stringify(data);
			
			this.socketTask.send({
				data: message,
				success: () => {
					console.log('WebSocket消息发送成功:', data);
				},
				fail: (err) => {
					console.error('WebSocket消息发送失败:', err);
					// 发送失败可能是连接断开了，尝试重连
					this.handleConnectionError();
				}
			});
		} else {
			console.warn('WebSocket未连接，无法发送消息:', data);
			// 如果未连接，可以将消息加入队列，连接成功后再发送
			this.notifyHandlers('sendFailed', data);
		}
	}

	/**
	 * 处理接收到的消息
	 * @param {Object} data 接收到的数据
	 */
	handleMessage(data) {
		const { type } = data;
		
		switch (type) {
			case 'pong':
				// 心跳响应
				break;
			case 'message':
			case 'userJoined':
			case 'userLeft':
			case 'system':
			default:
				this.notifyHandlers('message', data);
				break;
		}
	}

	/**
	 * 开始心跳
	 */
	startHeartbeat() {
		this.clearHeartbeat();
		this.heartbeatTimer = setInterval(() => {
			if (this.isConnected) {
				this.send({ type: 'ping', timestamp: Date.now() });
			}
		}, this.heartbeatInterval);
	}

	/**
	 * 清除心跳
	 */
	clearHeartbeat() {
		if (this.heartbeatTimer) {
			clearInterval(this.heartbeatTimer);
			this.heartbeatTimer = null;
		}
	}

	/**
	 * 清除重连定时器
	 */
	clearReconnectTimer() {
		if (this.reconnectTimer) {
			clearTimeout(this.reconnectTimer);
			this.reconnectTimer = null;
		}
	}

	/**
	 * 添加消息处理器
	 * @param {string} id 处理器ID
	 * @param {Function} handler 处理函数
	 */
	addMessageHandler(id, handler) {
		this.messageHandlers.set(id, handler);
	}

	/**
	 * 移除消息处理器
	 * @param {string} id 处理器ID
	 */
	removeMessageHandler(id) {
		this.messageHandlers.delete(id);
	}

	/**
	 * 通知所有消息处理器
	 * @param {string} event 事件类型
	 * @param {any} data 数据
	 */
	notifyHandlers(event, data) {
		this.messageHandlers.forEach((handler) => {
			try {
				handler(event, data);
			} catch (error) {
				console.error('消息处理器执行错误:', error);
			}
		});
	}

	/**
	 * 获取连接状态
	 */
	getConnectionStatus() {
		return {
			isConnected: this.isConnected,
			reconnectCount: this.reconnectCount,
			maxReconnectCount: this.maxReconnectCount
		};
	}

	/**
	 * 重置重连计数
	 */
	resetReconnectCount() {
		this.reconnectCount = 0;
	}

	/**
	 * 设置WebSocket服务器地址
	 * @param {string} url 服务器地址
	 */
	setUrl(url) {
		this.wsUrl = url;
	}

	/**
	 * 设置重连参数
	 * @param {Object} options 重连选项
	 * @param {number} options.maxCount 最大重连次数
	 * @param {number} options.interval 重连间隔(ms)
	 */
	setReconnectOptions(options = {}) {
		if (options.maxCount !== undefined) {
			this.maxReconnectCount = options.maxCount;
		}
		if (options.interval !== undefined) {
			this.reconnectInterval = options.interval;
		}
	}

	/**
	 * 设置心跳间隔
	 * @param {number} interval 心跳间隔(ms)
	 */
	setHeartbeatInterval(interval) {
		this.heartbeatInterval = interval;
		if (this.isConnected) {
			this.startHeartbeat(); // 重新开始心跳
		}
	}
}

// 创建全局单例
const wsManager = new WebSocketManager();

export default wsManager; 